﻿using BAL;
using DAL;
using DAL.DataProvider;
using DAL.DataTransferObject;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;

namespace Module.QLHoaDon
{
    public partial class frmChiTietHoaDon : Form
    {
        private HoaDon passDataHD;

        //In an
        int RowPerPage = 1, pageNum = 0;

        int sum = 0;
        int chietKhau = 0;
        int tienTra = 0;
        int tienKhach = 0;
        public frmChiTietHoaDon()
        {
            InitializeComponent();
        }

        public frmChiTietHoaDon(HoaDon hoaDon)
        {
            InitializeComponent();
            passDataHD = hoaDon;
            XemChiTietHoaDon(passDataHD);
        }

        private void frmChiTietHoaDon_Load(object sender, EventArgs e)
        {
            //Console.WriteLine("Load");
            XemChiTietHoaDon(passDataHD);
            btnUpdateChiTietHD.Enabled = false;
            btnDeleteChiTietHD.Enabled = false;
            GiamGiaKHBAO ggkhBAO = new GiamGiaKHBAO();
            //txtTongTien.Text = (Convert.ToDouble(txtTongTien.Text) - Convert.ToDouble(txtTongTien.Text) * ggkhBAO.GiamGiaKH_LayChietKhau(txtGGKhach.Text) / 100).ToString();
            //MessageBox.Show(ggkhBAO.GiamGiaKH_LayChietKhau(txtGGKhach.Text).ToString());
            txtSoDu.Text = (Convert.ToInt32(txtTienDua.Text) - Convert.ToInt32(txtTongTien.Text)).ToString();
            if (Convert.ToInt32(txtTienDua.Text) < Convert.ToInt32(txtTongTien.Text))
            {
                btnExitChiTiet.Enabled = false;
                btnUpdatePrice.Enabled = false;
            }
            txtTienDua.TextChanged += txtTienDua_TextChanged;
        }

        public void XemChiTietHoaDon(HoaDon hoadon)
        {
            //SqlCommand cmd = new SqlCommand("select HangHoa.MaHang,HangHoa.TenHang, HangHoa.SoLuongDongGoi, HangHoa.DonVi, HangHoa.VAT,ChiTietHoaDon.GiaTruocVAT" +
            //                                            ", ChiTietHoaDon.GiatruocVat*HangHoa.Vat/100+ChiTietHoaDon.GiaTruocVAT as ThanhTien from " +
            //                                            "HangHoa, ChiTietHoaDon where MaHoaDon=@maHD and HangHoa.MaHang=ChiTietHoaDon.MaHang", DataAccess.GetConnection());
            SqlCommand cmd = new SqlCommand("select MaHang,TenHang,SoLuongMua,DonVi, MaGiamGiaHang as MaGiamGia,GiaTruocVAT,VAT,ThanhTien " +
                "from view_ChiTietHoaDon where MaHoaDon=@MaHD", DataAccess.GetConnection());
            cmd.Parameters.AddWithValue("@maHD", hoadon.maHoaDon);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgvChiTietHoaDon.DataSource = dt;

            SqlDataAdapter daGGK = new SqlDataAdapter(String.Format("select MaGiamGiaKhach from HoaDon where MaHoaDon ='{0}'", passDataHD.maHoaDon), DataAccess.GetConnection());
            DataTable dtGGK = new DataTable();
            daGGK.Fill(dtGGK);
            txtGGKhach.Text = dtGGK.Rows[0].ItemArray[0].ToString();
            txtMaKH.Text = passDataHD.maKhachHang;
            txtMaThuNgan.Text = passDataHD.maNVThanhToan;
            txtMaHD.Text = passDataHD.maHoaDon;
            txtTienDua.Text = passDataHD.tienKhachDua.ToString();
            dtpkNgayIn.Value = passDataHD.ngayInHoaDon;
            dtpkNgayMua.Value = passDataHD.ngayMuaHang;
            txtTenKH.Text = this.GetTenKH(passDataHD.maKhachHang);
            txtTenThuNgan.Text = this.GetTenNV(passDataHD.maNVThanhToan);

            double thanhTien = 0;
            if (dt.Rows.Count >= 1)
                for (int i = 0; i < dt.Rows.Count; i++)
                    thanhTien += Convert.ToDouble(dt.Rows[i]["ThanhTien"].ToString());
            GiamGiaKHBAO ggkhBAO = new GiamGiaKHBAO();
            thanhTien = thanhTien - thanhTien * ggkhBAO.GiamGiaKH_LayChietKhau(txtGGKhach.Text) / 100;
            thanhTien = (int)thanhTien;
            txtTongTien.Text = thanhTien.ToString();
        }

        private string GetTenKH(string maKH)
        {
            string s = "";
            SqlCommand cmd = new SqlCommand("select TenKH from KhachHang where MaKH=@MaKH", DataAccess.GetConnection());
            cmd.Parameters.AddWithValue("@MaKH", maKH);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            s = dt.Rows[0]["TenKH"].ToString();
            return s;
        }

        private string GetTenNV(string maNV)
        {
            string s = "";
            //Console.WriteLine("tennv:" + maNV);
            SqlCommand cmd = new SqlCommand("select * from NhanVien where MaNV=@MaNV", DataAccess.GetConnection());
            cmd.Parameters.AddWithValue("@MaNV", maNV);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            s = dt.Rows[0]["TenNV"].ToString();
            return s;
        }

        private void btnDeleteChiTietHD_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Ban co chac chan muon xoa", "OOPS", MessageBoxButtons.YesNo);
            if (DialogResult.Yes == dialogResult)
            {
                SqlCommand cmd = new SqlCommand("delete from ChiTietHoaDon where MaHang=@Mahang and MaHoaDon=@maHD", DataAccess.GetConnection());
                cmd.Parameters.AddWithValue("@Mahang", dgvChiTietHoaDon.SelectedRows[0].Cells[0].Value.ToString());
                cmd.Parameters.AddWithValue("@maHD", txtMaHD.Text);
                int flag = cmd.ExecuteNonQuery();
                if (flag == 0)
                    MessageBox.Show("Xoa thanh cong !");
                else
                    MessageBox.Show("Xoa ko thanh cong !");
                btnRefresh.PerformClick();
            }
        }

        private void btnAddChiTietHD_Click(object sender, EventArgs e)
        {
            frmThemChiTietHoaDon frm = new frmThemChiTietHoaDon(txtMaHD.Text);
            frm.ShowDialog();
            btnRefresh.PerformClick();
        }

        ChiTietHoaDonBAO ctBAO = new ChiTietHoaDonBAO();

        private void btnUpdateChiTietHD_Click(object sender, EventArgs e)
        {
            ChiTietHoaDon obj = new ChiTietHoaDon();
            obj.maHoaDon = txtMaHD.Text;
            obj.maHang = dgvChiTietHoaDon.SelectedRows[0].Cells[0].Value.ToString();
            obj.soLuongMua = Convert.ToInt32(dgvChiTietHoaDon.SelectedRows[0].Cells[2].Value.ToString());
            obj.maGiamGiaHang = dgvChiTietHoaDon.SelectedRows[0].Cells[4].Value.ToString();
            obj.giaTruocVAT = Convert.ToInt32(dgvChiTietHoaDon.SelectedRows[0].Cells[5].Value.ToString());
            obj.VAT = Convert.ToInt32(dgvChiTietHoaDon.SelectedRows[0].Cells[6].Value.ToString());

            frmThemChiTietHoaDon frm = new frmThemChiTietHoaDon(obj);
            frm.ShowDialog();
            btnRefresh.PerformClick();
        }

        private void btnExitChiTiet_Click(object sender, EventArgs e)
        {
            btnUpdatePrice.PerformClick();
            this.Close();
        }

        private void dgvChiTietHoaDon_Click(object sender, EventArgs e)
        {

            btnUpdateChiTietHD.Enabled = true;
            btnDeleteChiTietHD.Enabled = true;
        }

        private void txtTienDua_TextChanged(object sender, EventArgs e)
        {
            //Console.WriteLine("TD" + txtTienDua.Parent.ToString());
            try
            {
                if (txtTienDua.Text != "" && txtTongTien.Text != "")
                    if (Convert.ToInt32(txtTienDua.Text) >= Convert.ToInt32(txtTongTien.Text))
                    {
                        GiamGiaKHBAO ggkhBAO = new GiamGiaKHBAO();
                        txtTongTien.Text = (Convert.ToInt32(txtTongTien.Text) - Convert.ToInt32(txtTongTien.Text) * ggkhBAO.GiamGiaKH_LayChietKhau(txtGGKhach.Text) / 100).ToString();
                        txtSoDu.Text = (Convert.ToInt32(txtTienDua.Text) - Convert.ToInt32(txtTongTien.Text)).ToString();
                        btnExitChiTiet.Enabled = true;
                        btnUpdatePrice.Enabled = true;
                    }
                    else
                    {
                        GiamGiaKHBAO ggkhBAO = new GiamGiaKHBAO();
                        txtTongTien.Text = (Convert.ToInt32(txtTongTien.Text) - Convert.ToInt32(txtTongTien.Text) * ggkhBAO.GiamGiaKH_LayChietKhau(txtGGKhach.Text) / 100).ToString();
                        txtSoDu.Text = (Convert.ToInt32(txtTienDua.Text) - Convert.ToInt32(txtTongTien.Text)).ToString();
                        btnExitChiTiet.Enabled = false;
                        btnUpdatePrice.Enabled = false;
                    }
            }
            catch (Exception)
            {
                MessageBox.Show("Du lieu nhap vao ko hop le!");
                txtTienDua.Text = txtTongTien.Text;
                txtTienDua.Focus();
            }
        }

        private void txtTienDua_Click(object sender, EventArgs e)
        {
            if (txtTienDua.IsDisposed)
                txtTienDua.TextChanged += txtTienDua_TextChanged;
        }

        HoaDonBAO hdBAO = new HoaDonBAO();
        private void btnUpdatePrice_Click(object sender, EventArgs e)
        {
            passDataHD.tienKhachDua = Convert.ToInt32(txtTienDua.Text);
            passDataHD.giamGiaKhach = txtGGKhach.Text;
            hdBAO.UpdateHoaDon(passDataHD);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            dgvChiTietHoaDon.Refresh();
            XemChiTietHoaDon(passDataHD);
            if (Convert.ToInt32(txtTienDua.Text) < Convert.ToInt32(txtTongTien.Text))
            {
                btnExitChiTiet.Enabled = false;
                btnUpdatePrice.Enabled = false;
            }
            txtSoDu.Text = (Convert.ToInt32(txtTienDua.Text) - Convert.ToInt32(txtTongTien.Text)).ToString();
        }



        private void btnPrint_Click(object sender, EventArgs e)
        {
            InHoaDon();
        }


        public void InHoaDon()
        {
            PrintDocument printDoc = new PrintDocument();
            printDialog.Document = printDoc;
            printDoc.DocumentName = "HoaDon_" + txtMaHD.Text + "_" + DateTime.Now.ToString();
            printDoc.PrintPage += PrintPageEvent;
            DialogResult result = printDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                printDoc.Print();
            }
        }

        KhachHangBAO khBAO = new KhachHangBAO();

        public string BlankSpace(string s, int n)
        {
            string tmp = "";
            for (int i = 0; i < n; i++)
                tmp += s;
            return tmp;
        }

        private void PrintPageEvent(object sender, PrintPageEventArgs e)
        {

            PrintDocument printDoc = sender as PrintDocument;

            DataView dv = ctBAO.SelectViewChiTietHoaDon(txtMaHD.Text);

            Graphics graph = e.Graphics;
            Font font = new Font("Segoe UI", 9);
            SolidBrush textColor = new SolidBrush(Color.Magenta);


            SqlCommand cmd;
            SqlDataAdapter da;
            DataTable dt;
            int delta = 0;

            int[] jumpSpaces = { 0, 70, 220, 55, 50, 70, 70, 70 };



            int startX = 10;
            int startY = 10;
            int fontH = font.Height;

            graph.DrawString("HANDSOME Cash & Carry VietNam", new Font("Segoe UI", 20), new SolidBrush(Color.Black), new Point(startX, startY));

            startY += fontH * 4;
            graph.DrawString("Thông tin khách hàng:", font, textColor, new Point(startX + 450, startY));
            graph.DrawString("Thông tin hóa đơn:", font, textColor, new Point(startX, startY));
            startY += fontH;
            graph.DrawString(("Mã khách hàng:" + dv.Table.Rows[0]["MaKH"].ToString()), font, textColor, new Point(startX + 450, startY));
            graph.DrawString("Mã hoa đơn:" + dv.Table.Rows[0]["MaHoaDon"].ToString(), font, textColor, new Point(startX, startY));
            startY += fontH;
            graph.DrawString(("Tên khách hàng:" + dv.Table.Rows[0]["TenKH"].ToString()), font, textColor, new Point(startX + 450, startY));
            graph.DrawString("Ngày mua hang:" + dv.Table.Rows[0]["NgayMuaHang"].ToString(), font, textColor, new Point(startX, startY));
            startY += fontH;
            graph.DrawString("Ngày in hóa đơn:" + dv.Table.Rows[0]["NgayInHoaDon"].ToString(), font, textColor, new Point(startX, startY));


            startY += fontH * 4;

            cmd = new SqlCommand("Select MaHoaDon,MaNVThanhToan, MaQT,MaGiamGiaKhach from view_ChiTietHoaDon where MaHoaDon=@mahd", DataAccess.GetConnection());
            cmd.Parameters.AddWithValue("@mahd", txtMaHD.Text);
            da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            DataView dsCTNV = new DataView(dt);
            //dv.RowFilter = String.Format("MaHoaDon='{0}'", txtMaHD.Text);
            for (int i = 0; i < dsCTNV.Table.Columns.Count; i++)
            {
                graph.DrawString(dsCTNV.Table.Columns[i].ToString() + ":" + dsCTNV.Table.Rows[0].ItemArray[i].ToString(), font, textColor, new Point(startX + 150 * i, startY));
                if (i == dsCTNV.Table.Columns.Count - 1)
                    graph.DrawString("Trang" + ":" + (pageNum + 1).ToString(), font, textColor, new Point(startX + 150 * (i + 2), startY));

            }

            cmd = new SqlCommand("Select MaHang, TenHang,DonVi,SoLuongMua as SL,MaGiamGiaHang as MaGG," +
            "GiaTruocVAT as GiaGoc, VAT,ThanhTien from view_ChiTietHoaDon where MaHoaDon=@mahd", DataAccess.GetConnection());
            cmd.Parameters.AddWithValue("@mahd", txtMaHD.Text);
            da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            DataView dvDSHang = new DataView(dt);

            startY += fontH;
            graph.DrawString(BlankSpace("-", 200), font, textColor, new Point(startX, startY));
            startY += fontH;
            delta = 0;
            for (int i = 0; i < dvDSHang.Table.Columns.Count; i++)
            {
                delta += jumpSpaces[i];
                graph.DrawString(dvDSHang.Table.Columns[i].ToString(), font, new SolidBrush(Color.Magenta), new Point(startX + delta, startY));
            }
            startY += fontH;
            graph.DrawString(BlankSpace("-", 200), font, textColor, new Point(startX, startY));
            startY += fontH;



            for (int i = pageNum + pageNum * (RowPerPage - 1); i < (pageNum + 1) * RowPerPage; i++)
            {
                delta = 0;
                if (dvDSHang.Table.Rows.Count == i)
                    break;
                for (int j = 0; j < dvDSHang.Table.Columns.Count; j++)
                {
                    delta += jumpSpaces[j];
                    if (j != 1)
                        graph.DrawString(dvDSHang.Table.Rows[i].ItemArray[j].ToString(), font, textColor, new Point(startX + delta, startY));
                }
                graph.DrawString(dvDSHang.Table.Rows[i].ItemArray[1].ToString().Substring(0, Math.Min(30, dvDSHang.Table.Rows[i].ItemArray[1].ToString().Length)), font, textColor, new Point(startX + jumpSpaces[1], startY));
                sum += (int)Convert.ToDouble(dvDSHang.Table.Rows[i]["ThanhTien"].ToString());
                startY += fontH;
            }
            graph.DrawString(BlankSpace("-", 200), font, textColor, new Point(startX, startY));

            if (pageNum < Math.Round((double)dv.Table.Rows.Count / RowPerPage, 1) - 1)
            {
                pageNum += 1;
                e.HasMorePages = true;
            }
            else
            {
                startY += fontH;
                graph.DrawString("Tổng cộng:", font, textColor, new Point(startX, startY));
                delta = 0;
                for (int i = 0; i < jumpSpaces.Length; i++)
                    delta += jumpSpaces[i];
                graph.DrawString(sum.ToString(), font, textColor, new Point(startX + delta, startY));
                startY += fontH;
                graph.DrawString("Mã giảm giá khách:", font, textColor, new Point(startX, startY));


                graph.DrawString(dv.Table.Rows[0]["MaGiamGiaKhach"].ToString(), font, textColor, new Point(startX + delta, startY));
                startY += fontH;
                GiamGiaKHBAO ggkBAO = new GiamGiaKHBAO();
                graph.DrawString("Triết khấu cho khách(%):", font, textColor, new Point(startX, startY));

                if (dv.Table.Rows[0]["MaGiamGiaKhach"].ToString() != "0")
                {
                    graph.DrawString(ggkBAO.GiamGiaKH_LayChietKhau(dv.Table.Rows[0]["MaGiamGiaKhach"].ToString()).ToString(), font, textColor, new Point(startX + delta, startY));
                    chietKhau = ggkBAO.GiamGiaKH_LayChietKhau(dv.Table.Rows[0]["MaGiamGiaKhach"].ToString());
                }
                else
                    graph.DrawString("0", font, textColor, new Point(startX + delta, startY));
                startY += fontH;
                tienTra = (sum - sum * chietKhau / 100);
                graph.DrawString("Tổng cộng tiền của khách:", font, textColor, new Point(startX, startY));
                graph.DrawString(tienTra.ToString(), font, textColor, new Point(startX + delta, startY));

                startY += fontH;
                tienKhach = Convert.ToInt32(dv.Table.Rows[0]["TienKhachDua"].ToString());
                graph.DrawString("Tiền khách đưa:", font, textColor, new Point(startX, startY));
                graph.DrawString(dv.Table.Rows[0]["TienKhachDua"].ToString(), font, textColor, new Point(startX + delta, startY));

                startY += fontH;
                graph.DrawString(BlankSpace("-", 200), font, textColor, new Point(startX, startY));
                startY += fontH;
                graph.DrawString("Tiền gửi khách:", font, textColor, new Point(startX, startY));
                graph.DrawString((tienKhach - tienTra).ToString(), font, textColor, new Point(startX + delta, startY));
            }
        }

        private void txtTienDua_KeyDown(object sender, KeyEventArgs e)
        {
        }




    }
}
